<template>
  <view class="register-container">
    <uni-card title="用户注册">
      <view class="input-group">
        <uni-easyinput
          v-model="registerForm.username"
          placeholder="请输入用户名"
          :clearable="true"
        />
      </view>
      
      <view class="input-group">
        <uni-easyinput
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码"
          :clearable="true"
        />
      </view>
      
      <view class="input-group">
        <uni-easyinput
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请确认密码"
          :clearable="true"
        />
      </view>

      <view class="btn-group">
        <button type="primary" @click="handleRegister">注册</button>
        <button @click="goToLogin">返回登录</button>
      </view>
    </uni-card>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  
  methods: {
    async handleRegister() {
      // 表单验证
      if (!this.registerForm.username || !this.registerForm.password) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
      
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        uni.showToast({
          title: '两次密码不一致',
          icon: 'none'
        })
        return
      }
      
      try {
        const res = await request({
          url: '/auth/register',
          method: 'POST',
          data: {
            username: this.registerForm.username,
            password: this.registerForm.password
          }
        })
        
        if (res.statusCode === 201) {
          uni.showToast({
            title: '注册成功'
          })
          // 注册成功后跳转到登录页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (e) {
        uni.showToast({
          title: '注册失败',
          icon: 'none'
        })
      }
    },
    
    goToLogin() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.register-container {
  padding: 30rpx;
  
  .input-group {
    margin-bottom: 30rpx;
  }
  
  .btn-group {
    margin-top: 50rpx;
    
    button {
      margin-bottom: 20rpx;
    }
  }
}
</style> 